package seiacpsjava.utilities;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MemoryService {

	private final ExecutorService executerService;
	private final MemoryRecorder memoryRecorder;
	private Future<MemoryStatistics> memoryFuture;
	
	public MemoryService() {
		executerService = Executors.newSingleThreadExecutor();
		this.memoryRecorder = new MemoryRecorder();
	}
	
	/**
	 * 
	 * @param recordingWaitTime the number of ms we should wait before reading the memory again
	 */
	public MemoryService(long recordingWaitTime) {
		executerService = Executors.newSingleThreadExecutor();
		this.memoryRecorder = new MemoryRecorder(recordingWaitTime);
	}
	
	/**
	 * starts a new thread which in our case is the MemoryRecorder
	 */
	public void startRecording() {
		memoryFuture = executerService.submit(this.memoryRecorder);
	}
	
	/**
	 * Ends the MemoryRecorder and retrieves the statistics of the memory consumption
	 * @return MemoryStatitics containing information about totalMemory, memoryUsed 
	 */
	public MemoryStatistics endRecording() {
		
		this.memoryRecorder.stopRecording();
		MemoryStatistics statistics = new MemoryStatistics();
		try {
			statistics = memoryFuture.get();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		this.executerService.shutdown();
		return statistics;
	}
}
